package com.wj.gulimall.order.config;

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

@Configuration
public class RabbitConfig {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Bean
    public MessageConverter messageConverter() {
        return new Jackson2JsonMessageConverter();
    }

    /**
     * 定制rabbitTemplate
     */
    @PostConstruct
    public void initRabbitTemplate() {
        /**
         * 确认回调
         * correlationData: 当前消息的唯一关联数据（id）
         * ack 是否成功收到
         * cause：失败原因
         */
        rabbitTemplate.setConfirmCallback((correlationData, ack, cause) -> {
            System.out.println("消息确认" + correlationData + ":" + ack + ":" + cause);
        });

        //消息尚未抵达队列：回调
        /**
         * message 投递失败的消息详细信息
         * replyCode 回复的状态码
         * replyText 回复的文本内容
         * exchange 交换机
         * routingKey 用哪个路由键
         */
        rabbitTemplate.setReturnCallback((message, replyCode, replyText, exchange, routingKey) -> {
            System.out.println(message + ":" + replyCode + ":" + replyText + ":" + exchange + ":" + routingKey);
        });
    }
}
